// order.ts - 呼叫立体救援页面

Page({
  data: {
    statusBarHeight: '44px',
    navbarHeight: '132rpx',
    
    // 地址信息
    startLocation: '王府井东大街 11号',
    startLocationDetail: '北京市东城区王府井东大街西路田号，发财胡同东侧魏家大院4号',
    startLocationData: null as any,
    endLocation: '',
    endLocationData: null as any,
    
    // 选择的车辆类型
    selectedType: 'ambulance',
    
    // 用车时间
    dateTab: 'specified' as 'specified' | 'today' | 'tomorrow',
    
    // 多列选择器数据
    multiArray: [
      ['9月1日', '9月2日', '9月3日', '9月4日', '9月5日', '9月6日', '9月7日', '9月8日', '9月9日', '9月10日', '9月11日', '9月12日'],
      ['08:00 - 08:30', '08:30 - 09:00', '09:00 - 09:30', '09:30 - 10:00', '10:00 - 10:30', '10:30 - 11:00', '11:00 - 11:30', '11:10 - 11:20', '11:30 - 12:00', '12:00 - 12:30', '12:10 - 12:20', '12:30 - 13:00', '13:00 - 13:30', '13:10 - 13:20', '13:30 - 14:00', '14:00 - 14:30', '14:10 - 14:20', '14:30 - 15:00', '15:00 - 15:30', '15:10 - 15:20', '15:30 - 16:00', '16:00 - 16:30', '16:30 - 17:00', '17:00 - 17:30'],
      ['上午', '下午']
    ],
    multiIndex: [10, 7, 0], // 默认选中 9月11日, 11:10 - 11:20, 上午
    
    // 显示的选中时间
    selectedDate: '9月11日',
    selectedTime: '11:10 - 11:20',
    selectedPeriod: '上午',
    
    // 转运紧急程度 - 改为下拉选择
    urgencyOptions: ['低（2天内）', '中（1天内）', '高（3小时内）'],
    urgencyIndex: 0,
    urgencyLevel: 'low' as 'low' | 'medium' | 'high',
    
    // 车辆随行人员 - 改为下拉选择
    passengerOptions: ['1人', '2人', '3人', '4人', '5人'],
    passengerIndex: 1,
    passengerCount: 2,
    
    // 病人情况描述
    patientDescription: '',
    patientImages: [] as string[],
    patientVideos: [] as string[],
    
    // 下单类型
    orderType: 'self' as 'self' | 'proxy',
    
    // 手机号码
    phoneNumber: '135 0000 0000'
  },

  onLoad() {
    this.setStatusBarHeight()
    this.checkLogin()
  },

  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().updateSelected(1)
    }
  },

  setStatusBarHeight() {
    const windowInfo = (wx as any).getWindowInfo()
    const statusBarHeight = windowInfo.statusBarHeight || 44
    const navbarContentHeight = 88 // rpx
    
    // 计算导航栏总高度（rpx单位）
    const statusBarHeightRpx = statusBarHeight * 2
    const navbarTotalHeight = statusBarHeightRpx + navbarContentHeight
    
    this.setData({
      statusBarHeight: statusBarHeight + 'px',
      navbarHeight: navbarTotalHeight + 'rpx'
    })
  },

  checkLogin() {
    const userRole = wx.getStorageSync('userRole')
    if (!userRole || userRole !== 'user') {
      wx.reLaunch({ url: '/pages/login/login' })
    }
  },

  goBack() {
    wx.switchTab({ url: '/pages/list-user/list-user' })
  },

  contactService() {
    wx.makePhoneCall({
      phoneNumber: '400-123-4567'
    })
  },

  selectStartLocation() {
    wx.navigateTo({
      url: '/pages/map-picker/map-picker?from=order&type=start'
    })
  },

  selectVehicleType(e: any) {
    const type = e.currentTarget.dataset.type
    const typeNames: Record<string, string> = {
      'ambulance': '救护车',
      'train': '高铁转运',
      'flight': '民用航班',
      'medical_plane': '医疗包机',
      'helicopter': '直升机'
    }
    
    this.setData({
      selectedType: type
    })
    
    // 给用户反馈
    wx.showToast({
      title: `已选择${typeNames[type]}`,
      icon: 'success',
      duration: 1500
    })
    
    console.log('选择车辆类型:', type, typeNames[type])
  },

  selectDateTab(e: any) {
    const tab = e.currentTarget.dataset.tab
    this.setData({
      dateTab: tab
    })
  },

  onMultiPickerChange(e: any) {
    const values = e.detail.value
    const multiArray = this.data.multiArray
    
    this.setData({
      multiIndex: values,
      selectedDate: multiArray[0][values[0]],
      selectedTime: multiArray[1][values[1]],
      selectedPeriod: multiArray[2][values[2]]
    })
    
    console.log('选中时间:', multiArray[0][values[0]], multiArray[1][values[1]], multiArray[2][values[2]])
  },

  onMultiPickerColumnChange(e: any) {
    const column = e.detail.column
    const value = e.detail.value
    const multiIndex = this.data.multiIndex
    multiIndex[column] = value
    
    this.setData({
      multiIndex: multiIndex
    })
  },

  onUrgencyChange(e: any) {
    const index = e.detail.value
    const levelMap = ['low', 'medium', 'high']
    this.setData({
      urgencyIndex: index,
      urgencyLevel: levelMap[index] as 'low' | 'medium' | 'high'
    })
    console.log('选择紧急程度:', this.data.urgencyOptions[index])
  },

  onPassengerChange(e: any) {
    const index = e.detail.value
    this.setData({
      passengerIndex: index,
      passengerCount: index + 1
    })
    console.log('选择人数:', this.data.passengerOptions[index])
  },

  onDescriptionInput(e: any) {
    this.setData({
      patientDescription: e.detail.value
    })
  },

  chooseImage() {
    const that = this
    wx.chooseMedia({
      count: 9 - this.data.patientImages.length,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFiles = res.tempFiles.map((file: any) => file.tempFilePath)
        that.setData({
          patientImages: [...that.data.patientImages, ...tempFiles]
        })
        wx.showToast({
          title: `已添加${tempFiles.length}张照片`,
          icon: 'success'
        })
      }
    })
  },

  chooseVideo() {
    const that = this
    wx.chooseMedia({
      count: 3 - this.data.patientVideos.length,
      mediaType: ['video'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFiles = res.tempFiles.map((file: any) => file.tempFilePath)
        that.setData({
          patientVideos: [...that.data.patientVideos, ...tempFiles]
        })
        wx.showToast({
          title: `已添加${tempFiles.length}个视频`,
          icon: 'success'
        })
      }
    })
  },

  previewImage(e: any) {
    const index = e.currentTarget.dataset.index
    wx.previewImage({
      current: this.data.patientImages[index],
      urls: this.data.patientImages
    })
  },

  deleteImage(e: any) {
    const index = e.currentTarget.dataset.index
    const images = this.data.patientImages
    images.splice(index, 1)
    this.setData({
      patientImages: images
    })
  },

  deleteVideo(e: any) {
    const index = e.currentTarget.dataset.index
    const videos = this.data.patientVideos
    videos.splice(index, 1)
    this.setData({
      patientVideos: videos
    })
  },

  selectDestination() {
    wx.navigateTo({
      url: '/pages/map-picker/map-picker?from=order&type=end'
    })
  },

  selectOrderType(e: any) {
    const type = e.currentTarget.dataset.type
    this.setData({
      orderType: type
    })
    console.log('选择下单类型:', type)
  },

  onPhoneInput(e: any) {
    this.setData({
      phoneNumber: e.detail.value
    })
  },

  submitOrder() {
    const { 
      selectedType, 
      startLocation, 
      endLocation, 
      phoneNumber,
      urgencyLevel,
      passengerCount,
      patientDescription
    } = this.data
    
    // 验证必填项
    if (!startLocation) {
      wx.showToast({
        title: '请选择出发地',
        icon: 'none'
      })
      return
    }
    
    if (!endLocation) {
      wx.showToast({
        title: '请选择目的地',
        icon: 'none'
      })
      return
    }
    
    if (!phoneNumber || phoneNumber.length < 11) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }
    
    // 车辆类型名称映射
    const typeNames: Record<string, string> = {
      'ambulance': '救护车',
      'train': '高铁转运',
      'flight': '民用航班',
      'medical_plane': '医疗包机',
      'helicopter': '直升机'
    }
    
    const orderData = {
      type: selectedType,
      typeName: typeNames[selectedType],
      startLocation,
      endLocation,
      urgencyLevel,
      passengerCount,
      patientDescription,
      phoneNumber,
      createTime: new Date().toISOString()
    }
    
    console.log('提交订单数据:', orderData)
    
    wx.showLoading({ title: '提交中...' })
    
    setTimeout(() => {
      wx.hideLoading()
      wx.showModal({
        title: '呼叫成功',
        content: `您的${typeNames[selectedType]}救援申请已提交，我们将尽快为您安排！`,
        showCancel: false,
        success: () => {
          wx.switchTab({ url: '/pages/list-user/list-user' })
        }
      })
    }, 1500)
  }
})
